const CHANNEL_ID = "notices_intercom";
const CHANNEL_NAME = "系统通知";
const CHANNEL_ID_CALL = "notices_intercom_call"; // 硬件按下（语音对讲）专用通道
const createdChannels = new Set();
let permissionChecked = false;
let hasNotificationPermission = true;
// 防抖：记录已处理的通知ID，避免一次启动过程中被多次处理
const handledNotifyIds = new Set();

/**
 * 检查当前系统API级别是否大于等于指定值
 */
function isApiLevelAtLeast(apiLevel) {
  if (typeof plus === 'undefined') return false;
  const Build = plus.android.importClass("android.os.Build");
  return Build.VERSION.SDK_INT >= apiLevel;
}

/**
 * 获取当前活动的主 Activity
 */
function getMainActivity() {
  if (typeof plus === 'undefined') {
    console.error('plus API 不可用，当前环境可能不是App端');
    return null;
  }
  return plus.android.runtimeMainActivity();
}

/**
 * 获取系统服务
 */
function getSystemService(serviceName) {
  const main = getMainActivity();
  if (!main) return null;

  const Context = plus.android.importClass("android.content.Context");
  return main.getSystemService(Context[serviceName]);
}

/**
 * 获取自定义通知铃声Uri（/static/Audio/message.mp3）
 */
function getCustomSoundUri(main) {
  try {
    if (!main) return null;
    const Uri = plus.android.importClass('android.net.Uri');
    const File = plus.android.importClass('java.io.File');
    const local = plus.io.convertLocalFileSystemURL('/static/Audio/message.mp3');
    if (!local) return null;
    if (/^file:\/\//.test(local)) {
      return Uri.parse(local);
    }
    const f = new File(local);
    return Uri.fromFile(f);
  } catch (e) {
    console.error('获取自定义铃声Uri失败:', e);
    return null;
  }
}

/**
 * 手动播放自定义通知铃声，避免通道被系统/用户覆盖
 */
function playCustomNotificationSound(soundPath = '/static/Audio/message.mp3') {
  try {
    const player = plus.audio.createPlayer(soundPath);
    player.play(() => {
      // 播放完成后释放
      try {
        player.stop();
      } catch (_) {}
    }, (err) => {
      console.error('自定义铃声播放失败:', err);
    });
  } catch (e) {
    console.error('创建自定义铃声播放器失败:', e);
  }
}

/**
 * 创建 PendingIntent（关键修改：使用唯一ID确保跳转意图正确）
 */
function createPendingIntent(main, intent, notifyId) {
  if (!main) return null;

  const PendingIntent = plus.android.importClass("android.app.PendingIntent");
  // 使用notifyId作为requestCode，确保每个通知的意图唯一
  const flags = PendingIntent.FLAG_CANCEL_CURRENT | (isApiLevelAtLeast(31) ? PendingIntent.FLAG_IMMUTABLE : 0);
  return PendingIntent.getActivity(main, notifyId, intent, flags);
}

/**
 * 检查通知权限（仅Android 13+）
 * @param {Function} callback - 回调函数，参数为 boolean (是否有权限)
 */
function checkNotificationPermission(callback) {
  if (permissionChecked) {
    callback(hasNotificationPermission);
    return;
  }

  // Android 13 以下默认有权限
  if (!isApiLevelAtLeast(33)) {
    hasNotificationPermission = true;
    permissionChecked = true;
    callback(true);
    return;
  }

  // Android 13+ 需要运行时权限
  const permissions = ["android.permission.POST_NOTIFICATIONS"];
  plus.android.requestPermissions(
    permissions,
    (result) => {
      hasNotificationPermission = result.granted && Array.isArray(result.granted) && result.granted.length > 0;
      permissionChecked = true;

      if (!hasNotificationPermission) {
        uni.showModal({
          title: "权限提醒",
          content: "请开启通知权限，否则无法接收消息通知",
          showCancel: false,
          confirmText: "知道了"
        });
      }
      callback(hasNotificationPermission);
    },
    (result) => {
      console.error("请求通知权限失败:", result);
      hasNotificationPermission = false;
      permissionChecked = true;
      uni.showModal({
        title: "权限请求失败",
        content: "请手动在应用设置中开启通知权限",
        showCancel: false
      });
      callback(false);
    }
  );
}

/**
 * 创建通知通道
 */
function createNotificationChannel(nm) {
  if (!isApiLevelAtLeast(26)) return;

  try {
    const NotificationManager = plus.android.importClass("android.app.NotificationManager");
    const NotificationChannel = plus.android.importClass('android.app.NotificationChannel');
    const IMPORTANCE_HIGH = NotificationManager.IMPORTANCE_HIGH;

    const channel = new NotificationChannel(
      CHANNEL_ID,
      CHANNEL_NAME,
      IMPORTANCE_HIGH
    );

    channel.enableVibration(true);
    channel.setVibrationPattern([100, 200, 100, 300]);
    channel.setLockscreenVisibility(1); // Notification.VISIBILITY_PUBLIC

    // 为避免被设备/用户通知设置覆盖导致不一致，这里禁用通道音效，改为手动播放固定音频
    channel.setSound(null, null);

    nm.createNotificationChannel(channel);
  } catch (e) {
    console.error("创建通知通道失败:", e);
  }
}

// 硬件按下（语音对讲）专用通道：设置固定通道和固定声音
function ensureCallChannel(nm) {
  if (!isApiLevelAtLeast(26)) return;
  try {
    if (createdChannels.has(CHANNEL_ID_CALL)) return;
    const main = getMainActivity();
    if (!main || !nm) return;
    const NotificationManager = plus.android.importClass("android.app.NotificationManager");
    const NotificationChannel = plus.android.importClass('android.app.NotificationChannel');
    const AudioAttributes = plus.android.importClass('android.media.AudioAttributes');
    const IMPORTANCE_HIGH = NotificationManager.IMPORTANCE_HIGH;

    const ch = new NotificationChannel(CHANNEL_ID_CALL, '通话通知', IMPORTANCE_HIGH);
    ch.enableVibration(true);
    ch.setVibrationPattern([100, 200, 100, 300]);
    ch.setLockscreenVisibility(1);

    // 绑定 calling_com.mp3 作为通道声音
    const Uri = plus.android.importClass('android.net.Uri');
    const File = plus.android.importClass('java.io.File');
    const local = plus.io.convertLocalFileSystemURL('/static/Audio/calling_com.mp3');
    if (local) {
      const useUri = /^file:\/\//.test(local) ? Uri.parse(local) : Uri.fromFile(new File(local));
      const attrs = new AudioAttributes.Builder()
        .setUsage(AudioAttributes.USAGE_NOTIFICATION)
        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
        .build();
      ch.setSound(useUri, attrs);
    } else {
      ch.setSound(null, null);
    }

    nm.createNotificationChannel(ch);
    createdChannels.add(CHANNEL_ID_CALL);
  } catch (e) {
    console.error('ensureCallChannel失败:', e);
  }
}

/**
 * 获取小图标资源 ID
 */
function getSmallIconId(main) {
  if (!main) return 17301620;

  try {
    const res = main.getResources();
    const pkg = main.getPackageName();

    // 优先使用自定义图标
    let id = res.getIdentifier("ic_notification", "drawable", pkg);
    if (id > 0) return id;

    // 降级：使用 app_icon（HBuilderX 默认图标）
    id = res.getIdentifier("app_icon", "drawable", pkg);
    if (id > 0) return id;

    // 最终降级：系统默认
    return 17301620;
  } catch (e) {
    return 17301620;
  }
}

/**
 * 构建通知
 */
function buildNotification(main, channelId, connect, pendingIntent) {
  if (!main || !pendingIntent) return null;

  const NotificationCompat = plus.android.importClass("androidx.core.app.NotificationCompat");
  const Notification = plus.android.importClass('android.app.Notification');

  const mNotification = new NotificationCompat.Builder(main, channelId);
  const smallIconId = getSmallIconId(main);

  mNotification
    .setSmallIcon(smallIconId)
    .setContentTitle(connect.title || '新通知')
    .setContentText(connect.content || '测试信息')
    .setAutoCancel(true)
    .setPriority(NotificationCompat.PRIORITY_HIGH)
    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
    .setVibrate([100, 200, 100, 300])
    .setCategory(NotificationCompat.CATEGORY_REMINDER)
    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
    .setContentIntent(pendingIntent); // 绑定点击意图

  // 统一不在通知上设置声音，改为手动播放，避免通道被覆盖导致不一致

  return mNotification.build();
}

/**
 * 创建并显示通知（核心逻辑）
 * @param {string} content - 通知内容
 * @param {object} data - 附加数据
 * @param {object} connect - 通知标题等配置
 * @param {string} [path='/pages/news/news'] - 点击跳转路径
 */
function createNotification(content = '', data = {}, connect = {}, path = '/pages/news/news', soundPath = null) {
  if (!isAppEnv() || plus.os.name !== 'Android') {
    console.error('当前环境不支持Android通知功能');
    return false;
  }

  checkNotificationPermission((granted) => {
    if (!granted) return;

    const main = getMainActivity();
    if (!main) return;

    const nm = getSystemService("NOTIFICATION_SERVICE");
    if (!nm) return;

    const NotifyID = Math.floor(Math.random() * 10000) + 1;
    const Intent = plus.android.importClass("android.content.Intent");
    const intent = new Intent(main, main.getClass());

    // 关键修改：添加跳转路径参数
    const payload = {
      'msg': content,
      'notify_id': NotifyID,
      'data': data,
      'path': path // 存储跳转路径
    };
    intent.putExtra("receive", JSON.stringify(payload));
    // 设置意图标志，确保正确唤醒应用
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    // 关键修改：传递notifyId确保意图唯一性
    const pendingIntent = createPendingIntent(main, intent, NotifyID);
    if (!pendingIntent) return;

    let targetChannel = CHANNEL_ID;
    if (isApiLevelAtLeast(26)) {
      // 如果是硬件按下发起的语音对讲（调用方传入 calling/call），使用专用通道并使用通道声音
      const isCallScene = typeof soundPath === 'string' && (soundPath.indexOf('calling') >= 0 || soundPath.indexOf(
        'call') >= 0);
      if (isCallScene) {
        ensureCallChannel(nm);
        targetChannel = CHANNEL_ID_CALL;
      } else {
        // 其他场景仍使用基础通道（基础通道静音，由手动播放覆盖）
        createNotificationChannel(nm);
        targetChannel = CHANNEL_ID;
      }
    } else {
      // 低版本直接用基础通道
      createNotificationChannel(nm);
    }

    const mNb = buildNotification(main, targetChannel, connect, pendingIntent);
    if (!mNb) return;

    try {
      nm.notify(NotifyID, mNb);
      console.log('通知发送成功:', NotifyID);
      // 呼叫通道不再手动播放，避免与通道声音冲突；其他场景继续手动播放
      const isCallScene = typeof soundPath === 'string' && (soundPath.indexOf('calling') >= 0 || soundPath.indexOf(
        'call') >= 0);
      if (!isCallScene) {
        const finalSound = soundPath || '/static/Audio/message.mp3';
        playCustomNotificationSound(finalSound);
      }
    } catch (e) {
      console.error('发送通知失败:', e);
      uni.showToast({
        title: '通知发送失败',
        icon: 'none'
      });
    }
  });

  return true;
}

/**
 * 处理通知点击事件（核心跳转逻辑）
 */
function handleNotification() {
  if (!isAppEnv() || plus.os.name !== 'Android') {
    return false;
  }

  try {
    const main = getMainActivity();
    const intent = main.getIntent();
    if (!intent) {
      return false;
    }

    // 兼容性获取字符串Extra
    let message = '';
    try {
      if (typeof intent.getStringExtra === 'function') {
        message = intent.getStringExtra('receive');
      } else if (typeof intent.getExtra === 'function') {
        message = intent.getExtra('receive');
      }
    } catch (e) {
      // 忽略
    }
    const parsedMessage = message ? JSON.parse(message) : null;

    if (parsedMessage && parsedMessage.notify_id) {
      const nm = getSystemService("NOTIFICATION_SERVICE");
      const notifyId = parsedMessage.notify_id;
      // 获取跳转路径，默认跳转到新闻页
      const targetPath = parsedMessage.path || '/pages/news/news';

      // 防重：相同ID的通知只处理一次
      if (handledNotifyIds.has(notifyId)) {
        return false;
      }
      handledNotifyIds.add(notifyId);

      // 取消通知
      if (nm && typeof nm.cancel === 'function') {
        nm.cancel(notifyId);
      }

      // 先清空意图中的数据，避免 onShow 再次触发时重复处理
      try {
        if (typeof intent.putExtra === 'function') {
          intent.putExtra('receive', '');
        }
      } catch (e) {}

      // 使用延迟，确保应用冷启动时页面栈已准备好
      setTimeout(() => {
        const pages = getCurrentPages();
        const normalized = targetPath.replace(/^\//, '');

        if (!pages || pages.length === 0) {
          // 冷启动：直接重启到目标页
          uni.reLaunch({
            url: targetPath
          });
          return;
        }

        // 顶部页面就是目标页，直接返回
        const top = pages[pages.length - 1];
        if (top && top.route === normalized) {
          return;
        }

        // 如果目标页存在于栈中，则回退到该页；否则直接打开
        const idx = pages.findIndex(p => p.route === normalized);
        if (idx >= 0) {
          const delta = pages.length - idx - 1;
          if (delta > 0) {
            uni.navigateBack({
              delta
            });
          }
        } else {
          uni.navigateTo({
            url: targetPath,
            success: () => {
              console.log('通知点击跳转成功:', targetPath);
            },
            fail: (err) => {
              console.error('navigateTo失败，尝试reLaunch:', err);
              uni.reLaunch({
                url: targetPath
              });
            }
          });
        }
      }, 250);
      return true;
    }
  } catch (e) {
    console.error('处理通知点击失败:', e);
  }

  return false;
}

/**
 * 检查当前环境是否为App环境
 */
function isAppEnv() {
  return typeof plus !== 'undefined';
}

// 发送通知
function showNotification() {

  const notificationData = {
    title: "新消息提醒",
    content: "这是一条测试通知，点击查看详情",
    ticker: "您有一条新消息"
  }

  // 附加数据（可选，点击通知时可获取）
  const extraData = {
    type: "system",
    id: "123456"
  };

  notificationData.content = uni.getStorageSync('nitificaValue')

  // 调用工具类发送通知
  const isSuccess = createNotification(
    notificationData.content, // 通知内容（与content字段一致即可）
    extraData, // 附加数据
    notificationData // 通知配置（标题、内容等）
  );

  // 修正：仅在非Android系统时才提示
  if (!isSuccess) {
    if (typeof plus !== 'undefined' && plus.os.name === 'Android') {
      console.log('通知发送失败（可能是权限未开启或其他原因）');
    } else {
      console.log('当前设备不支持（非Android系统）');
    }
  } else {
    console.log('通知发送成功');
  }
  // testNotification()
}

// 指定自定义声音的快捷方法
function showNotificationWithSound(soundPath) {
  const notificationData = {
    title: "新消息提醒",
    content: uni.getStorageSync('nitificaValue') || '您有一条新消息'
  };
  const extraData = {};
  return createNotification(notificationData.content, extraData, notificationData, '/pages/news/news', soundPath);
}



export {
  createNotification,
  showNotification,
  showNotificationWithSound,
  handleNotification,
  isAppEnv
};